package com.maoyongqi.springboot06.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController  {

    @Autowired
    RedisTemplate redisTemplate;

    public static Boolean IsScan = false;

    @RequestMapping("/index")
    public String Index(HttpSession session){
        UUID uuid = UUID.randomUUID();
        System.out.println("进入页面，生成uuid" +
                uuid);
        session.setAttribute("uuid",uuid);

        return "index";
    }

    @RequestMapping("/qrcode/{uuid}")
    @ResponseBody
    public  String createQRcode(@PathVariable("uuid") String uuid, HttpServletResponse response){
        System.out.println("生成二维码中");

//        String text = "http://127.0.0.1:8080/login/"+ uuid;
        String text = "http://192.168.88.118:8080/login/"+uuid;

        int width = 300;
        int height = 300;
        String format = "png";

        redisTemplate.opsForValue().set("uuid",uuid);
        redisTemplate.expire("uuid",6, TimeUnit.MINUTES);
        try
        {
            Map<EncodeHintType, Object> hints;
            hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //hints.put(EncodeHintType.MARGIN, 1);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错率
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
            MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
        } catch (WriterException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("二维码生成完成");
        return null;
    }

    @RequestMapping("/pool")
    @ResponseBody
    public String pool(String uuid){
        System.out.println("检测[" + uuid + "]是否登录");

            return null;
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                // task to run goes here
//                System.out.println("Hello !!");
//            }
//        };
//        ScheduledExecutorService service = Executors
//                .newSingleThreadScheduledExecutor();
//        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
//        service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);
}

    @RequestMapping("/login/{uuid}")
    @ResponseBody
    public String Login(@PathVariable("uuid")String verify){
        String uuid = redisTemplate.opsForValue().get("uuid").toString();
        if (uuid == null){
            return "uuid request timeout";
        }
        if(uuid.equals(verify)){
            IsScan = true;
        }
        return "login success";
    }
}
